package cn.htu.edu.controller;

import cn.htu.edu.common.ResponseHelper;
import cn.htu.edu.common.ResponseModel;
import cn.htu.edu.config.EasyExcelConfig;
import cn.htu.edu.entity.Users;
import cn.htu.edu.mapper.PersonMapper;
import cn.htu.edu.entity.Person;
import cn.htu.edu.service.IPersonService;
import cn.htu.edu.utils.StringUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dakai
 * @since 2024-05-10
 */
@RestController
@Api(value = "person表接口",tags = "person表接口")
@RequestMapping("/person")
public class PersonController {

    @Resource
    private IPersonService iPersonService;

    @Resource
    private PersonMapper personMapper;

    @Resource
    private EasyExcelConfig<Person> easyExcelConfig;

    @ApiOperation("removeByIds批量删除")
    @PostMapping("/delete")
    public ResponseModel delete(@RequestBody String[] ids) {
        iPersonService.removeByIds(Arrays.asList(ids));
        return ResponseHelper.buildResponseModel("删除成功");
    }

    @ApiOperation("ids批量删除")
    @PostMapping("delete1")
    public ResponseModel delete1(@RequestBody Map<String,Object> map) {
        List<String> ids = Arrays.asList(map.get("ids").toString().split(","));
        iPersonService.delete(ids);
        return ResponseHelper.buildResponseModel("删除成功");
    }

    @ApiOperation("循环批量删除")
    @PostMapping("delete2")
    public ResponseModel delete2(@RequestBody String[] ids) {
        for (String id: ids) {
            personMapper.deletePerson(id);
        }
        return ResponseHelper.buildResponseModel("删除成功");
    }

    /**
     * 导出带分页数据
     */
    @GetMapping("IPageExportExcel")
    public void exportData(HttpServletResponse response,Integer pageNo, Integer pageSize) throws IOException {
        // ... 导出数据代码 ...
        IPage<Person> p = new Page<>(pageNo, pageSize);
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户表", String.valueOf(StandardCharsets.UTF_8)).replaceAll("\\+", "%20");
        List<Person> personList = personMapper.importExcel(p).getRecords();
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Person.class).sheet("用户表").doWrite(personList);
    }

    /**
     * 导出数据
     */
    @GetMapping("exportExcel")
    public void exportData1(HttpServletResponse response) throws IOException {
        // ... 导出数据代码 ...
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("用户表", String.valueOf(StandardCharsets.UTF_8)).replaceAll("\\+", "%20");
        List<Person> personList = iPersonService.list();
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), Person.class).sheet("用户表").doWrite(personList);
    }

    @PostMapping("/read")
    public ResponseModel read(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(),Person.class,easyExcelConfig)
                .sheet()  //excel中表的名称，默认为第一个sheet
                .doRead();
        List<Person> data = easyExcelConfig.getData();
        //将读取到的数据存入数据库中
        for (Person person: data) {
            person.setId(StringUtil.createUUID());
            personMapper.insert(person);
        }
        return ResponseHelper.buildResponseModel("导入成功");
    }

    @PostMapping("/importExcel")
    public ResponseModel importExcel(@RequestParam("file") MultipartFile file) {
        try {
            iPersonService.importExcel(file);
            return ResponseHelper.buildResponseModel("导入成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseHelper.buildResponseModel("导入失败");
        }
    }

}
